package com.it.gw.modules.water.fragment

import LoginVo
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.it.common.utils.DisplayUtil
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.isNotEmpty
import com.it.data.manager.AppCacheManager
import com.it.data.network.rsp.WaterRecordListVo
import com.it.gw.base.BaseFragment
import com.it.gw.databinding.FragmentWaterRecordBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.modules.water.activity.WaterMainActivity
import com.it.gw.modules.water.activity.pump.PumpItemDetailActivity
import com.it.gw.modules.water.activity.shoubu.ShouBuItemDetailActivity
import com.it.gw.modules.water.activity.sluice.SluiceItemDetailActivity
import com.it.gw.modules.water.adapter.WaterRecordAdapter
import com.tencent.mmkv.MMKV

class WaterRecordFragment : BaseFragment<FragmentWaterRecordBinding>() {
    private val datas by lazy { mutableListOf<WaterRecordListVo>() }
    private val adapter by lazy {
        WaterRecordAdapter(context = requireActivity(), datas = datas, listener = {
            Log.d(TAG, "${it.style} ")
            //WAGA 水闸  SHBU 首部  PUST 泵站
            if (it.style == "WAGA") {
                val intent = Intent(requireActivity(), SluiceItemDetailActivity::class.java)
                intent.putExtra("title", it.stnm)
                intent.putExtra("guid", it.guid)
                intent.putExtra("state", it.state)
                intent.putExtra("type", it.type)
                //opinion表示审核
                intent.putExtra("operationType", "opinion")
                startActivity(intent)
            }
            if (it.style == "PUST") {
                val intent = Intent(requireActivity(), PumpItemDetailActivity::class.java)
                intent.putExtra("title", it.stnm)
                intent.putExtra("guid", it.guid)
                intent.putExtra("state", it.state)
                intent.putExtra("type", it.type)
                //opinion表示审核
                intent.putExtra("operationType", "opinion")
                startActivity(intent)
            }
            if (it.style == "SHBU") {
                val intent = Intent(requireActivity(), ShouBuItemDetailActivity::class.java)
                intent.putExtra("title", it.stnm)
                intent.putExtra("guid", it.guid)
                intent.putExtra("state", it.state)
                intent.putExtra("type", it.type)
                //opinion表示审核
                intent.putExtra("operationType", "opinion")
                startActivity(intent)
            }


        })
    }

    companion object {
        const val PAGE_SIZE = 20
        const val TAG = "WaterRecordFragment"
    }

    private var pageNum = 1

    @SuppressLint("NotifyDataSetChanged")
    override fun initObserver() {
        (requireActivity() as WaterMainActivity).waterViewModel.waterRecordVoLiveData.observe(this) {
            ProgressDialog.hide()
            loadMoreData = false
            binding.swipeRefreshLayout.isRefreshing = false
            if (it.result) {
                if (it.data?.list.isNullOrEmpty()) {
                    Log.d(TAG, "initObserver: myWorkOrderVoListLiveData ${it.data?.list}")
                    if (pageNum > 1) {
                        pageNum--
                        Toast.makeText(requireActivity(), "没有更多数据了！", Toast.LENGTH_SHORT)
                            .show()
                    } else {
                        //第一次就没数据
                        datas.clear()
                        adapter.notifyDataSetChanged()
                    }

                } else {
                    if (pageNum == 1) {
                        datas.clear()
                    }
                    datas.addAll(it.data!!.list!!)
                    Log.d(TAG, "initObserver: pageGQStationVoListLiveData ${datas}")
                    adapter.notifyDataSetChanged()

                }
            } else {
                Toast.makeText(requireActivity(), "${it.msg}", Toast.LENGTH_LONG).show()
            }


        }

    }

    override fun initListener() {
        binding.swipeRefreshLayout.setOnRefreshListener {
            pageNum = 1
            getData()
        }
        binding.rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 获取布局管理器
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager

                // 获取最后一个可见的 item 的位置
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

                // 获取总的 item 数量
                val totalItemCount = layoutManager.itemCount

                // 判断是否滑动到了底部
                if (totalItemCount >= PAGE_SIZE && lastVisibleItemPosition == totalItemCount - 1) {
                    // 滑动到了底部，执行相关操作
                    loadMoreData()
                }
            }
        })

    }


    override fun initData() {

    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    private var loadMoreData = false;
    private fun loadMoreData() {
        if (loadMoreData) {
            return
        }
        Log.d(TAG, "loadMoreData: ")
        pageNum += 1
        loadMoreData = true;
        getData()
    }


    private fun getData() {
        val loginVo = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)
        (requireActivity() as WaterMainActivity).waterViewModel.applicationList(
            pageNum = pageNum,
            pageSize = PAGE_SIZE,
            addvcd = loginVo?.depId
        );

    }

    override fun initView() {
        val map = hashMapOf(
            RvSpacesItemUtils.BOTTOM_DECORATION to DisplayUtil.dip2px(
                requireActivity(),
                5f
            )
        )
        binding.rvList.addItemDecoration(RvSpacesItemUtils(map))
        binding.rvList.adapter = adapter
    }

    override fun getView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentWaterRecordBinding.inflate(layoutInflater)
        return binding.root
    }

}